<template>
  <div>
    <tool-header title="工作台-小铃铛">
      <q-btn @click="handleClick()" color="secondary">新增</q-btn>
    </tool-header>
    <q-table
        :data="schedules"
        :columns="columns"
        :table-colspan="pageSize"
        :pagination.sync="pagination"
        row-key="_id"
        separator="cell"
        :loading="isLoading">
      <template v-slot:body-cell-rule="props">
        <q-td :props="props">
          <div v-if="props.row.rule.year!==null">
            在 {{ props.row.rule.year }} 年
          </div>
          <div v-if="props.row.rule.date!==null">
            每月第 {{ props.row.rule.date }} 天
          </div>
          <div v-if="props.row.rule.dayOfWeek!==null">
            每周第 {{ props.row.rule.dayOfWeek }} 天
          </div>
          <div v-if="props.row.rule.hour!==null">
            每天第 {{ props.row.rule.hour }} 小时
          </div>
          <div v-if="props.row.rule.minute!==null">
            每小时第 {{ props.row.rule.minute }} 分钟
          </div>
          <div v-if="props.row.rule.second!==null">
            每分钟第 <span></span>{{ props.row.rule.second }} 秒
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-opt="props">
        <q-td :props="props">
          <q-btn class="q-mx-sm" @click="handleDelete(props.row)" color="amber">删除</q-btn>
          <q-btn class="q-mx-sm" @click="handleClick(props.row)" color="primary">编辑</q-btn>
        </q-td>
      </template>
    </q-table>
    <q-dialog v-model="dialogVisible" title="机器人配置">
      <q-card class="q-pa-lg" style="max-width: 680px">
        <q-input label="名称" v-model="form.name" placeholder="请输入名称"></q-input>
        <h6 class="text-h6 q-my-md">时间规则配置</h6>
        <div class="row">
          <q-input class="col-11" label="年份" type="number"
                   v-model.number="form.rule.year"
                   :disable="!form.ruleValid.year"
                   :rules="[ val => (val <= 22030 && val >= 2021) || !val  || '年份需要在 2021-2200 之间' ]"
          ></q-input>
          <q-checkbox v-model="form.ruleValid.year" @input="form.rule.year=null"/>
        </div>
        <div class="row">
          <q-input class="col-11" label="每月第几天" type="number"
                   v-model.number="form.rule.date"
                   :disable="!form.ruleValid.date"
                   :rules="[ val => (val <= 31 && val >= 1) || !val  || '天数需要在 1-31 之间' ]"
          ></q-input>
          <q-checkbox v-model="form.ruleValid.date" @input="form.rule.date=null"/>
        </div>
        <div class="row">
          <q-field label="每周第几天" stack-label>
            <template v-slot:control>
              <q-checkbox indeterminate-value="partial" v-model="checkAll" label="全选" color="teal"
                          @input="handleCheckAllChange"/>
              <q-option-group
                  v-model="form.rule.dayOfWeek" :options="qDays" @input="handleCheckedDayChange"
                  type="checkbox" color="green" inline
              />
            </template>
          </q-field>
        </div>
        <div class="row">
          <q-input class="col-11" label="每天第几小时" type="number"
                   v-model.number="form.rule.hour"
                   :disable="!form.ruleValid.hour"
                   :rules="[ val => (val <= 23 && val >= 0) || !val  || '小时需要在 0-23 之间' ]"
          ></q-input>
          <q-checkbox v-model="form.ruleValid.hour" @input="form.rule.hour=null"/>
        </div>
        <div class="row">
          <q-input class="col-11" label="每小时第几分钟" type="number"
                   v-model.number="form.rule.minute"
                   :disable="!form.ruleValid.minute"
                   :rules="[ val => (val <= 23 && val >= 0) || !val  || '分钟需要在 0-59 之间' ]"
          ></q-input>
          <q-checkbox v-model="form.ruleValid.minute" @input="form.rule.minute=null"/>
        </div>
        <div class="row">
          <q-input class="col-11" label="每分钟第几秒" type="number"
                   v-model.number="form.rule.second"
                   :disable="!form.ruleValid.second"
                   :rules="[ val => (val <= 59 && val >= 0) || !val  || '秒数需要在 0-59 之间' ]"
          ></q-input>
          <q-checkbox v-model="form.ruleValid.second" @input="form.rule.second=null"/>
        </div>
        <h6 class="text-h6 q-my-md">微信机器人配置</h6>
        <q-input label="Webhook 地址" v-model="form.webhookUrl" placeholder="请输入Webhook地址"></q-input>
        <h6 class="text-h6 q-my-md">钉钉机器人配置</h6>
        <q-input label="钉钉AccessToken" v-model="form.accessToken" placeholder="请输入secret（钉钉）"></q-input>
        <q-input label="钉钉加签" v-model="form.secret" placeholder="请输入钉钉加签（钉钉）"></q-input>
        <h6 class="text-h6 q-my-md">飞书机器人配置</h6>
        <q-input label="Webhook 地址" v-model="form.feishuWebhookUrl" placeholder="请输入Webhook地址"></q-input>
        <q-input label="消息内容" v-model="form.message" placeholder="请输入消息内容"></q-input>
        <q-card-section class="text-right">
          <q-btn class="q-ml-md" @click="dialogVisible = false">取 消</q-btn>
          <q-btn class="q-ml-md" type="primary" @click="submit()" :loading="isLoading">确 定</q-btn>
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>

import iRobot from '../../api/robot'
import ToolHeader from 'pages/ToolMangement/components/ToolHeader'

const defaultForm = {
  _id: null,
  name: '',
  rule: {
    second: null,
    minute: null,
    hour: null,
    date: null,
    year: null,
    dayOfWeek: []
  },
  ruleValid: {
    second: false,
    minute: false,
    hour: false,
    date: false,
    year: false
  },
  message: '',
  webhookUrl: '',
  accessToken: '',
  secret: '',
  feishuWebhookUrl: ''
}

const copy = (obj) => JSON.parse(JSON.stringify(obj))

export default {
  components: {
    ToolHeader
  },
  name: 'Robot',
  data () {
    return {
      dialogVisible: false,
      schedules: [],
      form: copy(defaultForm),
      qDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'].map((e, index) => ({
        label: e,
        value: index === 6 ? 0 : index + 1
      })),
      isLoading: false,
      checkAll: false,
      columns: [
        { name: 'name', label: '名称', field: 'name', sortable: true, align: 'left' },
        { name: 'message', label: '消息内容', field: 'message', sortable: true, align: 'left' },
        { name: 'utime', label: '更新时间', field: 'utime', sortable: true, align: 'left' },
        // {name: 'webhookUrl', label: 'Webhook地址', field: 'webhookUrl', sortable: true, align: 'left'},
        // {name: 'accessToken', label: '钉钉AccessToken', field: 'accessToken', sortable: true, align: 'left'},
        { name: 'rule', label: '触发规则', sortable: true, align: 'left' },
        { name: 'opt', label: '操作', sortable: true, align: 'middle' }
      ],
      pagination: {
        page: 1,
        rowsPerPage: 10,
        sortBy: 'utime',
        descending: true
      },
      pageNo: 1,
      pageSize: 10
    }
  },
  async mounted () {
    await this.initList()
  },
  methods: {
    async initList () {
      const resSchedules = await iRobot.getAllSchedule()
      this.schedules = resSchedules.map(schedule => {
        if (!Array.isArray(schedule.rule.dayOfWeek)) {
          schedule.rule.dayOfWeek = [schedule.rule.dayOfWeek].filter(e => e !== null)
        }
        schedule.ruleValid = {
          second: this.isValid(schedule.rule.second),
          minute: this.isValid(schedule.rule.minute),
          hour: this.isValid(schedule.rule.hour),
          date: this.isValid(schedule.rule.date),
          year: this.isValid(schedule.rule.year)
        }
        return schedule
      })
      console.log(this.schedules)
    },
    handleClick (schedule) {
      if (schedule) {
        this.form = copy(schedule)
      } else {
        this.form = copy(defaultForm)
      }
      this.dialogVisible = true
    },
    async submit () {
      const schedule = copy(this.form)
      schedule.rule.second = schedule.ruleValid.second ? schedule.rule.second : null
      schedule.rule.minute = schedule.ruleValid.minute ? schedule.rule.minute : null
      schedule.rule.hour = schedule.ruleValid.hour ? schedule.rule.hour : null
      schedule.rule.date = schedule.ruleValid.date ? schedule.rule.date : null
      schedule.rule.year = schedule.ruleValid.year ? schedule.rule.year : null
      try {
        this.isLoading = true
        if (this.form._id) {
          await iRobot.schedules.put(schedule, {
            pathParams: {
              id: schedule._id
            }
          })
        } else {
          await iRobot.createSchedule(schedule)
        }
      } catch (err) {
        this.$notify.error(err)
      } finally {
        this.isLoading = false
      }
      this.dialogVisible = false
      await this.initList()
    },
    handleDelete (schedule) {
      this.$q.dialog({
        title: '删除确认',
        message: '确认是否要删除？',
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await iRobot.schedules.delete({}, {
          pathParams: {
            id: schedule._id
          }
        })
        await this.initList()
      })
    },
    isValid (value) {
      return (value !== undefined) && (value !== null)
    },
    handleCheckAllChange (val) {
      this.form.rule.dayOfWeek = val ? [0, 1, 2, 3, 4, 5, 6] : []
    },
    handleCheckedDayChange () {
      const checkedCount = (this.form.rule.dayOfWeek || []).length
      if (checkedCount > 0 && checkedCount < 7) {
        this.checkAll = 'partial'
        return
      }
      if (checkedCount === 7) {
        this.checkAll = true
        return
      }
      this.checkAll = false
    }
  }
}</script>
<style>

</style>
